﻿using BaseDal;
using Models;
using System;
using System.Collections.Generic;
using System.Data;

namespace BaseBll
{
    public class PurchaseRequestBll
    {
        private static readonly Lazy<PurchaseRequestBll> dal = new Lazy<PurchaseRequestBll>(() => new PurchaseRequestBll());
        public static PurchaseRequestBll Instance { get; } = dal.Value;

        private PurchaseRequestBll()
        { }

        /// <summary>
        /// 查询数据是否存在
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public bool IsExist(string strWhere)
        {
            return PurchaseRequestDal.Instance.IsExist(strWhere);
        }

        /// <summary>
        /// 查询分页数据
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="strWhere"></param>
        /// <param name="filedOrder"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetPageList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            return PurchaseRequestDal.Instance.GetPageList(pageSize, pageIndex, strWhere, filedOrder, out recordCount);
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public List<PurchaseRequestHead> GetList(string strWhere)
        {
            return PurchaseRequestDal.Instance.GetList(strWhere);
        }

        /// <summary>
        /// 根据id查询实体类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PurchaseRequestHead GetModelById(int id)
        {
            return PurchaseRequestDal.Instance.GetModelById(id);
        }

        /// <summary>
        /// 根据单号查询实体类
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public PurchaseRequestHead GetModelByNo(string number)
        {
            return PurchaseRequestDal.Instance.GetModelByNo(number);
        }

        /// <summary>
        /// 通过申请单号与 物品编号获取物品
        /// </summary>
        /// <param name="number"></param>
        /// <param name="itemID"></param>
        /// <returns></returns>
        public PurchaseRequestBody GetItemByNoAndItemID(string number, string itemID)
        {
            return PurchaseRequestDal.Instance.GetItemByNoAndItemID(number, itemID);
        }

        /// <summary>
        /// 根据主表ID查询所有物品
        /// </summary>
        /// <param name="headID"></param>
        /// <returns></returns>
        public List<PurchaseRequestBody> GetItemList(int headID)
        {
            return PurchaseRequestDal.Instance.GetItemList(headID);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool AddPurchaseRequest(PurchaseRequestHead model)
        {
            return PurchaseRequestDal.Instance.AddPurchaseRequest(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool UpdatePurchaseRequest(PurchaseRequestHead model)
        {
            return PurchaseRequestDal.Instance.UpdatePurchaseRequest(model);
        }

        /// <summary>
        /// 删除一条数据，及子表所有相关数据
        /// </summary>
        public bool DeletePurchaseRequest(int ID)
        {
            return PurchaseRequestDal.Instance.DeletePurchaseRequest(ID);
        }

        /// <summary>
        /// 修改状态（0：审批中；1：已审批；2：暂存）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int UpdateStatus(int id, int status)
        {
            return PurchaseRequestDal.Instance.UpdateStatus(id, status);
        }

        /// <summary>
        /// 验证model各字段合法性
        /// </summary>
        /// <param name="model"></param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public bool VerifyModel(PurchaseRequestHead model, ref string msg)
        {
            string strWhere;
            if (model.ID > 0)
            {
                strWhere = " and PR_ApplyNo='" + model.PR_ApplyNo + "' and ID !=" + model.ID;
            }
            else
            {
                strWhere = " and PR_ApplyNo='" + model.PR_ApplyNo + "'";
            }
            if (IsExist(strWhere))
            {
                msg = "申请编号已存在";
                return false;
            }

            // 获取公司名称
            Department company = DeptBll.Instance.GetModelById(model.PR_CompanyId);
            if (company != null)
            {
                model.PR_CompanyName = company.FullName;
            }
            else
            {
                msg = "所选公司不存在";
                return false;
            }

            // 获取部门名称
            Department dept = DeptBll.Instance.GetModelById(model.PR_DeptId);
            if (dept != null)
            {
                model.PR_DeptName = dept.FullName;
            }
            else
            {
                msg = "所选部门不存在";
                return false;
            }

            // 获取供应商名称
            Supplier supplier = SupplierBll.Instance.GetModelById(model.PR_SupplierId);
            if (supplier != null)
            {
                model.PR_SupplierName = supplier.S_Name;
            }
            else
            {
                msg = "所选供应商不存在";
                return false;
            }

            return true;
        }

        // 定义一个私有的对象作为锁
        private readonly object _lockObject = new object();

        /// <summary>
        /// 采购订单审核通过时，修改申请单的"PR_BuyQty（已购买数量）" 字段
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdRequestWithAudit(List<PurchaseOrderBody> bodyList)
        {
            //  是否需要加锁？
            lock (_lockObject)
            {
                PurchaseRequestBody requestBody;
                List<PurchaseRequestBody> requestBodyList = new List<PurchaseRequestBody>();
                foreach (PurchaseOrderBody orderBody in bodyList)
                {
                    requestBody = null;
                    if (!string.IsNullOrEmpty(orderBody.PO_ApplyNo))
                    {
                        requestBody = Instance.GetItemByNoAndItemID(orderBody.PO_ApplyNo, orderBody.PO_ItemID);
                        if (requestBody != null)
                        {
                            requestBody.PR_BuyQty += orderBody.PO_BuyQty;
                            requestBodyList.Add(requestBody);
                        }
                    }
                }
                bool res = PurchaseRequestDal.Instance.UpdateReadyQty(requestBodyList);
                return res;
            }
        }
    }
}